package com.hk.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hk.constant.CacheConstants;
import com.hk.constant.HttpStatus;
import com.hk.context.BaseContext;
import com.hk.core.PageResult;
import com.hk.core.roleResult.PageRoleResult;
import com.hk.domain.*;
import com.hk.dto.*;
import com.hk.mapper.BusinessMapper;
import com.hk.mapper.ClueHistoryMapper;
import com.hk.mapper.ClueMapper;
import com.hk.mapper.ContractMapper;
import com.hk.service.ClueService;
import com.hk.vo.ClueBusinContractVo;
import com.hk.vo.ClueagsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper,Clue> implements ClueService  {
    @Autowired
    ClueMapper clueMapper;
    @Autowired
    ClueHistoryMapper clueHistoryMapper;
    @Autowired
    BusinessMapper businessMapper;

    @Autowired
  ContractMapper contractMapper;
    public static final Integer TRUE=1;
    public static final Integer TRUEING=2;
    public static final Integer CHANGE=0;
    public static final Integer T=0;
    public static final Integer F=1;




    /**
     * 添加线索
     * @param dto
     */
    @Override
    public void add(ClueDto dto) {
        Clue clue = new Clue();
        BeanUtils.copyProperties(dto,clue);
        clue.setOwner(BaseContext.getCurrent().getUserName());
        clue.setStatus(TRUE);
        clueMapper.insert(clue);
    }

    /**
     * 查看线索列表
     * @return
     */
    @Override
    public PageResult list(CluePageDto dto) {
        Page<Clue> page = new Page<>(dto.getPageNum(), dto.getPageSize());


        Page<Clue> p = clueMapper.selectPage(page, Wrappers.<Clue>lambdaQuery()
                .in(Clue::getStatus,  TRUE, TRUEING).
                eq(Clue::getAuthenticity, T)
                .like(ObjectUtils.isNotEmpty(dto.getId()), Clue::getId, dto.getId())
                .like(StringUtils.isNotBlank(dto.getPhone()), Clue::getPhone, dto.getPhone()).
                like(StringUtils.isNotBlank(dto.getOwner()), Clue::getOwner, dto.getOwner()).
                like(ObjectUtils.isNotEmpty(dto.getChannel()), Clue::getChannel, dto.getChannel()).
                like(ObjectUtils.isNotEmpty(dto.getStatus()), Clue::getStatus, dto.getStatus()).apply(hasDateRange(dto),
                "DATE_FORMAT(create_time, '%Y-%m-%d') BETWEEN DATE_FORMAT({0}, '%Y-%m-%d') AND DATE_FORMAT({1}, '%Y-%m-%d')",
                dto.getParams().get("beginCreateTime"),
                dto.getParams().get("endCreateTime")));


        PageResult pageResult = new PageResult();
        pageResult.setCode(200);
        pageResult.setTotal((int) p.getTotal());
        pageResult.setRows(p.getRecords());
        pageResult.setMsg("认证成功");
        return pageResult;
    }

    /**
     * 查看单条线索
     * @return
     */
    @Override
    public Clue queryById(Integer id) {
        Clue clue = clueMapper.selectById(id);
        return clue;
    }

    /**
     * 修改线索表
     * @param dto
     */
    @Override
    public void updateClue(ClueUpdateDto dto) {
        Clue clue = new Clue();
        clue.setId(dto.getClueId());
        clue.setStatus(TRUEING);
        BeanUtils.copyProperties(dto,clue);
        ClueHistory clueHistory = new ClueHistory();
        BeanUtils.copyProperties(dto,clueHistory);
        clueMapper.updateById(clue);
        clueHistoryMapper.insert(clueHistory);
    }

    /**
     * 根据线索id查看线索历史表
     */
    @Override
    public PageResult listClueHistory(Integer clueId) {
        Page<ClueHistory> page = new Page<>(T, 10);
        Page<ClueHistory> p = clueHistoryMapper.selectPage(page, Wrappers.
                <ClueHistory>lambdaQuery().eq(ClueHistory::getClueId, clueId));
        PageResult pageResult = new PageResult();
        pageResult.setMsg("认证成功");
        pageResult.setCode(200);
        pageResult.setTotal((int) p.getTotal());
        pageResult.setRows(p.getRecords());
        return pageResult;
    }

    /**
     * 转为商机表
     * @param id
     */
    @Override
    public void changeBusiness(Integer id) {
        Clue clue = clueMapper.selectById(id);
        Business business = new Business();
        BeanUtils.copyProperties(clue,business);
        business.setStatus(TRUEING);
        business.setClueId(clue.getId());
        businessMapper.insert(business);
        clue.setStatus(CHANGE);
        clueMapper.updateById(clue);
    }

    //推到线索池
    @Override
    public int push(Integer id) {
        int i = clueMapper.update(Wrappers.<Clue>lambdaUpdate().set(Clue::getAuthenticity, 1).eq(Clue::getId, id));
        return i;
    }

    //查询线索池
    @Override
    public PageResult listPoll(CluePageDto dto) {
        Page<Clue> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        Page<Clue> p = clueMapper.selectPage(page, Wrappers.<Clue>lambdaQuery()
                .eq(Clue::getAuthenticity, F)
                .like(ObjectUtils.isNotEmpty(dto.getId()), Clue::getId, dto.getId())
                .like(StringUtils.isNotBlank(dto.getPhone()), Clue::getPhone, dto.getPhone()).
                like(ObjectUtils.isNotEmpty(dto.getChannel()), Clue::getChannel, dto.getChannel())
                .apply(hasDateRange(dto),
                        "DATE_FORMAT(create_time, '%Y-%m-%d') BETWEEN DATE_FORMAT({0}, '%Y-%m-%d') AND DATE_FORMAT({1}, '%Y-%m-%d')",
                        dto.getParams().get("beginCreateTime"),
                        dto.getParams().get("endCreateTime")));

        PageResult pageResult = new PageResult();
        pageResult.setCode(200);
        pageResult.setTotal((int) p.getTotal());
        pageResult.setRows(p.getRecords());
        pageResult.setMsg("认证成功");
        return pageResult;
    }

    //从线索池取数据
    @Override
    public void pull(PullDto dto) {
        List<Clue> clues = clueMapper.selectList(Wrappers.<Clue>lambdaQuery().in(Clue::getId, dto.getIds()));
        clues.forEach((i)->{
            i.setOwner("admin");
            i.setAuthenticity(T);
            i.setStatus(TRUE);
        });
        super.updateBatchById(clues);
    }

    @Override
    public Map<String, Long> selectCount() {
        QueryWrapper<Clue> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("owner", "count(*) as cluecount");
        queryWrapper.groupBy("owner");

        List<Map<String, Object>> result = clueMapper.selectMaps(queryWrapper);
//        转换成Map集合
        Map<String, Long> clueresult = result.stream()
                .collect(Collectors.toMap(
                        map -> (String) map.get("owner"),
                        map -> (Long) map.get("cluecount")
                ));

        log.info("何煜的方法");
        return clueresult;

    }


    /**
     * 辅助方法
     */
    private boolean hasDateRange(CluePageDto dto) {
        return ObjectUtils.isNotEmpty(dto.getParams()) &&
                ObjectUtils.isNotEmpty(dto.getParams().get("beginCreateTime")) &&
                ObjectUtils.isNotEmpty(dto.getParams().get("endCreateTime"));
    }


    @Override
    public Report getReport(LocalDate beginTime, LocalDate endTime) {
        Report report = new Report();
        ArrayList<LocalDate> xAxis = new ArrayList<>();
        LocalDate begin = beginTime;
        while (begin.isBefore(endTime)) {
            xAxis.add(begin);
            begin = begin.plusDays(1);
        }
        List<Integer> TaotalData=new ArrayList<>();
//因为数据库等级太低，出此下策
        for (LocalDate xAxi : xAxis) {
            //LocalDateTime  begin1 = LocalDateTime.of(xAxi, LocalTime.MIN);
            LocalDateTime end1 = LocalDateTime.of(xAxi, LocalTime.MAX);
            Integer  total = clueMapper.getClueCount(end1);
            TaotalData.add(total);
        }
        List<Integer> ClueData=new ArrayList<>();
        for (LocalDate xAxi : xAxis) {
            LocalDateTime  begin1 = LocalDateTime.of(xAxi, LocalTime.MIN);
            LocalDateTime  end1 = LocalDateTime.of(xAxi, LocalTime.MAX);
            Integer  total = clueMapper.getClueDatas(begin1,end1);
            ClueData.add(total);
        }
        report.setXAxis(xAxis);

        com.hk.domain.ClueData clueData1 = new ClueData();
        clueData1.setData(TaotalData);
        clueData1.setName("线索总数量");
        ClueData clueData2 = new ClueData();
        clueData2.setData(ClueData);
        clueData2.setName("线索总数量");
        ArrayList<ClueData> list = new ArrayList<>();
        list.add(clueData1);
        list.add(clueData2);
        report.setSeries(list);


        return report;
    }

    @Override
    public PageRoleResult listReport(ClueBusinContractDto clueBusinContractDto) {

        Page<Clue> cluePage = new Page<>(clueBusinContractDto.getPageNum(), clueBusinContractDto.getPageSize());
//        LambdaQueryWrapper<Clue> wrapper = new LambdaQueryWrapper<>();
//        wrapper.like(ObjectUtils.isNotEmpty(clueBusinContractDto.getOwner()), Clue::getOwner, clueBusinContractDto.getOwner());
//        wrapper.eq(ObjectUtils.isNotEmpty(clueBusinContractDto.getId()),  Clue::getId, clueBusinContractDto.getId());
//        wrapper.between(ObjectUtils.isNotEmpty(clueBusinContractDto.getBeginCreateTime())&&ObjectUtils.isNotEmpty(clueBusinContractDto.getEndCreateTime()), Clue::getCreateTime, clueBusinContractDto.getBeginCreateTime(), clueBusinContractDto.getEndCreateTime());
        IPage<ClueBusinContractVo> page = clueMapper.selectALL(cluePage, clueBusinContractDto);

        PageRoleResult result = new PageRoleResult();
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg(CacheConstants.LOGIN_SUCCESS1);
        result.setTotal((int) page.getTotal());
        result.setRows(page.getRecords());
        return result;
    }

    @Override
    public ClueagsVo Tjclus(LocalDateTime beginTime, LocalDateTime endTime) {
        ClueagsVo clueagsVo = new ClueagsVo();
        Integer cluesNums = clueMapper.getClueCount2(beginTime,endTime);
        Integer effectiveCluesNums = clueMapper.getClueStatusCount(beginTime, endTime);
        Integer businessNums = businessMapper.getBusinessCount(beginTime, endTime);
        Integer contractNums = contractMapper.getContractCount(beginTime, endTime);
        clueagsVo.setCluesNums(cluesNums);
        clueagsVo.setEffectiveCluesNums(effectiveCluesNums);
        clueagsVo.setBusinessNums(businessNums);
        clueagsVo.setContractNums(contractNums);
        return clueagsVo;
    }



}
